package com.virtual.rerijaapps.pet.utils;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;

import com.virtual.rerijaapps.pet.PrincipalScreen;
import com.virtual.rerijaapps.pet.R;
import com.virtual.rerijaapps.pet.data.Event;
import com.virtual.rerijaapps.pet.data.PetData;

public class DialogHelper 
{

	public static void showDialogRemovePet( final PrincipalScreen screen, final int whichPet )
	{
		AlertDialog.Builder builder = new AlertDialog.Builder( screen );
		builder.setTitle( R.string.delete_pet_title );
		builder.setMessage( R.string.confirm_delete_pet );
		builder.setPositiveButton( R.string.pet_delete, new OnClickListener() 
		{
			@Override
			public void onClick( DialogInterface dialog, int which ) 
			{
				final com.virtual.rerijaapps.pet.data.dao.EventDao eventDao = new com.virtual.rerijaapps.pet.data.dao.EventDao( screen );
				com.virtual.rerijaapps.pet.data.dao.PetDataDao petDataDao = new com.virtual.rerijaapps.pet.data.dao.PetDataDao( screen );
				
				Event exampleEvent = new Event();
				exampleEvent.setPetdatafk( ( ( PetData )screen.mPetAdapter.getItem( whichPet ) ).getId() );
				
				final List<Event> listEvents = eventDao.listByExample( exampleEvent );
				
				if ( null != listEvents &&  0 != listEvents.size() )
				{
					screen.showLoadingDialog( true );
					Thread threadDelete = new Thread( new Runnable() 
					{
						@Override
						public void run() 
						{
							for ( Event evento : listEvents )
							{
								CalendarHelper.deleteEventDefaultCalendar( screen, evento.getCalendarevent() );
								eventDao.delete( evento.getId() );
								Log.i( "EVENT_DELETE", "Event eliminado, ID: " +  evento.getId() );
							}
							screen.completeDialog();
						}
					} );
					threadDelete.start();
				}
	            
				petDataDao.delete( ( ( PetData )screen.mPetAdapter.getItem( whichPet ) ).getId() );
				Log.i( "PETDATA_DELETE", "PetData eliminado, ID: " + ( ( PetData )screen.mPetAdapter.getItem( whichPet ) ).getId() );
				
				screen.mPetAdapter.removePet( whichPet );
				screen.mPetAdapter.notifyDataSetChanged();
				screen.checkPets();
				dialog.cancel();
			}
		} );
		builder.setNegativeButton( R.string.cancel, new OnClickListener() 
		{
			@Override
			public void onClick( DialogInterface dialog, int which ) 
			{
				screen.mPetAdapter.notifyDataSetChanged();
				dialog.cancel();
			}
		} );
		
		builder.show();
		
	}
	
}
